package com.kitty.game.activity.service.task;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.ActivityDataPool;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.model.product.RandomNpcParam;
import com.kitty.game.activity.model.product.ShuaDaoRewardSet;
import com.kitty.game.activity.model.product.shuadao.ShuaDaoSet;
import com.kitty.game.activity.model.product.shuadao.XiangYaoShuaDaoSet;
import com.kitty.game.activity.service.ActivityService;
import com.kitty.game.activity.service.vip.SuperVipService;
import com.kitty.game.artifact.ArtifactService;
import com.kitty.game.base.service.BagService;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossNpcParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.config.GameMap;
import com.kitty.game.config.MapBossPos;
import com.kitty.game.config.NPC;
import com.kitty.game.config.TaskSet;
import com.kitty.game.confirm.model.FetchShuaDaoRewardConfirm;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.Position;
import com.kitty.game.enter.RespOpenShuadaoDlg;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.item.model.PointItem;
import com.kitty.game.item.service.PointItemService;
import com.kitty.game.mail.model.Mail;
import com.kitty.game.mail.service.MailService;
import com.kitty.game.map.service.MapService;
import com.kitty.game.npc.message.RespAutoWalk;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.player.model.PlayerExtendBox;
import com.kitty.game.rank.model.record.ShuaDaoRankRecord;
import com.kitty.game.rank.service.handler.*;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.task.message.RespTasksDel;
import com.kitty.game.task.message.vo.TaskInfo;
import com.kitty.game.task.model.product.TaskType;
import com.kitty.game.task.service.NewTaskService;
import com.kitty.game.team.message.RespConfirm;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.BitSet;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.task.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.concurrent.ThreadLocalRandom;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**刷道任务处理类*/
@Component
@Slf4j
public class ShuaDaoTaskHandler extends TaskActivityHandler{
    @Autowired
    ActivityService activityService;
    @Autowired
    PointItemService pointItemService;
    @Autowired
    BagService bagService;
    @Autowired
    EquipService equipService;

    /**最少组队人数*/
    private static final int MIN_TEAM_COUNT = 1;
    /**队员之间最大等级差*/
    private static final int MAX_LEVEL_DIFF = 10;
    /**每10轮扣除如意刷道令点数*/
    private static final int RYSDL_COUNT = 10;
    private static final String SHUADAO_NOT_FOUND = "找不到对应的刷道任务！[离开]";
    private static final String ACCEPT_TEAM_COUNT_NOT_ENOUGH = "此去凶险，还是组满#R{0}#n人再来找我吧！[离开]";
    private static final String FIGHT_TEAM_COUNT_NOT_ENOUGH = "连#R{0}#n个人都没有就想跟我斗？[离开]";
    private static final String FIGHT_LEVEL_NOT_ENOUGH = "{0}等级不足{1}级，竟然想来凑热闹，还是先去提升实力吧！[离开]";
    private static final String ACCEPT_TEAM_LEVEL_DIFF_MORE = "队伍中的成员的最大等级差超过了#R{0}级#n，无法进行组队{1}！[离开]";
    private static final String FIGHT_TEAM_LEVEL_DIFF_MORE = "队伍中的成员的最大等级差超过了#R{0}级#n！[离开]";
    private static final String ACCEPTED = "你已经领取#R{0}#n任务，还不快去降伏妖魔。[离开]";
    private static final String MESSAGE_TEMPLATE = "前往#Y#Z{0}#Z#n附近消灭#R{1}#n。";
    /**Boss从属于别的玩家时的提示*/
    private static final String NOT_YOU = "本座修炼数百年来未曾遇过对手，想来真是寂寞啊！[离开]";
    /**在战斗状态中的提示*/
    private static final String IN_FIGHT = "别烦我，没见我正忙着吗？[离开]";

    private static final String REWARD_NOT_IN_TEAM = "当前不在队伍中，无法获得奖励。";
    /**不能获得金币的最小刷道次数*/
    private static final int MIN_COUNT_NO_MONEY = 800;
    /**获得金币减半的最小刷道次数*/
    private static final int MIN_COUNT_HALF_MONEY = 400;

    /**通过NpcId获得刷道配置数据*/
    public ShuaDaoSet getShuaDaoSet(int npcId,int type) {
        if(type == 2){
            return ActivityDataPool.shuaDaoMap2.get(npcId);
        }
        return ActivityDataPool.shuaDaoMap.get(npcId);
    }

    /**通过任务Id获得刷道配置数据*/
    public ShuaDaoSet getShuaDaoSetByTask(Role role,int taskId) {
        int shuadaoLevel = role.getPropsStatus().getInt("shuadao_state", 0);
        if(shuadaoLevel == 2){
            return ActivityDataPool.shuaDaoMapByTask2.get(taskId);
        }
        return ActivityDataPool.shuaDaoMapByTask.get(taskId);
    }
    /**获得刷道十轮耗时秒数*/
    public short getTenShuaDaoUsedTime(Role role, ActivityType activityType) {
        if (activityType == null){
            return 0;
        }
        Map<String, Integer> tenShuaDaoUsedTime = role.getActivity().getTenShuaDaoUsedTime();
        Integer minUsedTime = tenShuaDaoUsedTime.get(activityType.getActivityId());
        if (minUsedTime == null) {
            return 0;
        }

        return minUsedTime.shortValue() < 60 ? 600:minUsedTime.shortValue();
    }

    @Override
    public TaskSet getAcceptingTask(Role role, NPC npc) {
        int shuadaoLevel = role.getPropsStatus().getInt("shuadao_state", 0);

        ShuaDaoSet shuaDaoSet = getShuaDaoSet(npc.getId(),shuadaoLevel);

        if (shuaDaoSet != null) {
            return taskService.getTaskSet(shuaDaoSet.getFightTaskId(), role);
        }

        return null;
    }

    @Override
    public String canAcceptTask(Role role, TaskSet taskSet, boolean auto) {
        if (taskSet == null) {
            return SHUADAO_NOT_FOUND;
        }
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        if (shuaDaoSet == null) {
            return SHUADAO_NOT_FOUND;
        }
//注释
//        if (auto && SpringUtils.getActivityService().getFinishCount(role, shuaDaoSet.getActivityType()) % 10 == 0
//               && (!pointItemService.isOpen(role, PointItem.RU_YI_SHUA_DAO_LING) || pointItemService.getPoint(role, PointItem.RU_YI_SHUA_DAO_LING) < RYSDL_COUNT)) {
//            /**返回空串，表示不能自动接取下一任务*/
//           return "";
//        }

        /**判断是否队伍有3人*/
        TeamService teamService = SpringUtils.getBean(TeamService.class);
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return MessageFormat.format(ACCEPT_TEAM_COUNT_NOT_ENOUGH, MIN_TEAM_COUNT);
        }

        /**判断所有人等级是否满足*/
        StringBuilder levelNotEnoughNames = new StringBuilder();
        Team team = teamService.getTeam(role.getRoleId());
        ArrayList<Member> members = team.getList();
        for (Member member : members) {
            if (member == null) {continue;}
            if (member.isInTeam() == false) {continue;}

            if (member.getLevel() >= shuaDaoSet.getMinLevel()) {continue;}

            if (levelNotEnoughNames.length() > 0) {
                levelNotEnoughNames.append("、");
            }
            levelNotEnoughNames.append(member.getName());
        }
        if (levelNotEnoughNames.length() > 0) {
            return MessageFormat.format(shuaDaoSet.getLevelNotEnoughDesc(), levelNotEnoughNames, shuaDaoSet.getMinLevel());
        }

        /**判断所有人等级差是否超过限制*/
        for(int i=0, count=members.size(); i<count; i++) {
            Member member = members.get(i);
            if(member == null || member.isInTeam() == false) {continue;}

            for (int j=i; j<count; j++) {
                Member otherMember = members.get(j);
                if(otherMember == null || otherMember.isInTeam() == false) {continue;}

                if (Math.abs(member.getLevel()-otherMember.getLevel()) > MAX_LEVEL_DIFF) {
                    return MessageFormat.format(ACCEPT_TEAM_LEVEL_DIFF_MORE, MAX_LEVEL_DIFF, shuaDaoSet.getShuaDaoName());
                }
            }
        }

        /**判断是否已经接取*/
        Role leader = SpringUtils.getRoleService().getOnlinePlayer(team.getLeaderUid());
        int npcId = leader.getTask().getTaskNpcId(shuaDaoSet.getFightTaskId());
        NPC npc = SpringUtils.getMapService().getNpc(npcId);
        if (npcId > 0 && npc != null) {
            /**判断所有玩家的任务目标是一致的，是一致的，则返回已接取提示*/
            boolean isMemberOtherTarget = false;
            for (Member member : team.getList()) {
                if (member == null) {continue;}
                /**暂离的不用判断*/
                if (member.isInTeam() == false) {continue;}

                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                if (memberRole == null) {continue;}

                int memberNpcId = memberRole.getTask().getTaskNpcId(shuaDaoSet.getFightTaskId());

                /**有一个成员的目标NPC与队长的NPC不一致时，就设置为true*/
                if (memberNpcId != npcId) {
                    isMemberOtherTarget = true;
                    break;
                }
            }

            if (isMemberOtherTarget == false) {
                return MessageFormat.format(ACCEPTED, shuaDaoSet.getShuaDaoName());
            }
        }

        return null;
    }

    @Override
    public void doBeforeAccept(Role role, TaskSet taskSet) {
        /**接取前先删除任务*/
        deleteTask(role, taskSet);
    }

    @Override
    public void doAfterAccept(Role role, TaskSet taskSet) {
        super.doAfterAccept(role, taskSet);

        TaskInfo taskInfo = getFightTaskInfo(role, taskSet);
        autoWalk(role, taskInfo);

        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());

        /**获得引导任务数据，隐藏之前的引导任务*/
        TaskSet guideTaskSet = taskService.getTaskSet(shuaDaoSet.getGuideTaskId(), role);
        RespTasksDel respTasksDel = taskService.getRespTasksDel(role, guideTaskSet.getTaskName());
        teamService.pushMessage(role, respTasksDel);

        /**扣除如意刷道令点数*/
        if (SpringUtils.getActivityService().getFinishCount(role, shuaDaoSet.getActivityType()) % 10 == 0
               && pointItemService.isOpen(role, PointItem.RU_YI_SHUA_DAO_LING)) {
            pointItemService.subtractRuYiShuaDaoLing(role, RYSDL_COUNT);
        }
    }

    @Override
    public String getNpcContent(Role role, NPC bossNpc) {
        String contentNotStart = getNpcContentNotFight(role, bossNpc);
        if (contentNotStart != null) {
            return contentNotStart;
        }

        TaskSet taskSet = getTaskSetByBossNpc(role, bossNpc);
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        return shuaDaoSet != null ? shuaDaoSet.getContent() : "";
    }

    private TaskInfo getFightTaskInfo(Role role, TaskSet taskSet) {
        if (taskSet == null) {return null;}

        int taskNpcId = role.getTask().getTaskNpcId(taskSet.getId());
        MapService mapService = SpringUtils.getBean(MapService.class);
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        NPC npc = mapService.getNpc(taskNpcId);
        if (npc == null) {
            log.error("刷道任务找不到对应NPC，roleId: {}, taskId: {}, npcId: {}", role.getRoleId(), taskSet.getId(), taskNpcId);
            return null;
        }

        GameMap gameMap = mapService.getMap(npc.getMapId());
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        int doStep = (activityService.getFinishCount(role, shuaDaoSet.getActivityType())%10) + 1;
        long remainMinute = (npc.getEndTime() > System.currentTimeMillis() ? ((npc.getEndTime() - System.currentTimeMillis()) / Const.MINUTE) : 0);
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setQuit((short) taskSet.getGiveUp());// 是否可以放弃
        taskInfo.setTaskName(taskSet.getTaskName());
        taskInfo.setShow_name(taskSet.getTaskName() +MessageFormat.format( "({0}/10)",doStep));
        if(shuaDaoSet.getFightTaskId()==91){
            /**飞仙渡邪有个总次数*/
            taskInfo.setTaskInfo(MessageFormat.format(taskSet.getTaskJieshao(), doStep, gameMap.getName(), npc.getName(), gameMap.getName(), npc.getX(), npc.getY(), remainMinute,activityService.getFinishCount(role, shuaDaoSet.getActivityType())));
        }else {
            taskInfo.setTaskInfo(MessageFormat.format(taskSet.getTaskJieshao(), doStep, gameMap.getName(), npc.getName(), gameMap.getName(), npc.getX(), npc.getY(), remainMinute));
        }
        taskInfo.setTaskZhiyin(MessageFormat.format( taskSet.getTaskZhiyin(),npc.getName(),gameMap.getName(),npc.getX(),npc.getY()));
        taskInfo.setTaskJiangli(taskSet.getTaskGift());
        return taskInfo;

    }

    /**自动寻路*/
    private void autoWalk(Role role, TaskInfo taskInfo) {
        RespAutoWalk respAutoWalk = new RespAutoWalk();
        respAutoWalk.setTaskName(taskInfo.getTaskName());
        respAutoWalk.setDest(taskInfo.getTaskZhiyin());
        MessagePusher.pushMessage(role, respAutoWalk);
    }

    @Override
    public TaskInfo getTaskInfo(Role role, TaskSet taskSet) {
        return getFightTaskInfo(role, taskSet);
    }

    @Override
    public String getPrompt(NPC npc) {
        GameMap map = SpringUtils.getBean(MapService.class).getMap(npc.getMapId());
        return MessageFormat.format(MESSAGE_TEMPLATE, map.getName(), npc.getName());
    }

    @Override
    public BossNpcParam newBossNpcParam(Role role, TaskSet taskSet) {
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        BossNpcParam bossNpcParam = new BossNpcParam();

        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        RandomNpcParam randomNpcParam = shuaDaoSet.getRandomNpcParam();
        BossSet bossSet = bossService.getBossSet(randomNpcParam.getBossName());
        bossNpcParam.setNpcIcon(bossSet.getIcon());
        bossNpcParam.setBossSetName(bossSet.getName());

        int randomMapId = shuaDaoSet.getRandomMapId();
        MapBossPos mapBossPos = bossService.getMapBossPos(randomMapId);
        Position position = bossService.getRandomPosition(mapBossPos);
        bossNpcParam.setMapId(mapBossPos.getMapId());
        bossNpcParam.setPosition(position);
        bossNpcParam.setMapId(16100);
        Position position1 = new Position();
        position1.setX((short) 37);
        position1.setY((short) 27);
        bossNpcParam.setPosition(position1);

        bossNpcParam.setDirection(shuaDaoSet.getDirection());
        bossNpcParam.setShowTimeSec(shuaDaoSet.getShowTimeSecond());

        bossNpcParam.setNpcName(randomNpcParam.getNpcName());


        bossNpcParam.setNpcType(NPC.TYPE_SHUA_DAO);
        /**属于哪个玩家*/
        bossNpcParam.setRoleUid(role.getUid());

        bossNpcParam.setBroad(true);


        return bossNpcParam;
    }

    @Override
    public TaskType getTaskType() {
        return TaskType.SHUA_DAO;
    }

    @Override
    public String getNpcContentNotFight(Role role, NPC bossNpc) {
        /**挑战玩家 不是对应玩家时*/
        if (bossNpc.getRoleUid() != role.getUid()) {
            /**在战斗状态时*/
            if (bossNpc.isInFight()) {
                return IN_FIGHT;
            }

            return NOT_YOU;
        }

        if (bossNpc.getType() != NPC.TYPE_SHUA_DAO) {
            /**理论上不应该会出现这个，防止客户端改了数据*/
            return NOT_YOU;
        }

        /**判断是否队伍有3人*/
        TeamService teamService = SpringUtils.getBean(TeamService.class);
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return MessageFormat.format(FIGHT_TEAM_COUNT_NOT_ENOUGH, MIN_TEAM_COUNT);
        }

        TaskSet taskSet = getTaskSetByBossNpc(role, bossNpc);
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        if (shuaDaoSet == null) {
            return SHUADAO_NOT_FOUND;
        }


        /**判断所有人等级是否满足*/
        StringBuilder levelNotEnoughNames = new StringBuilder();;
        Team team = teamService.getTeam(role.getRoleId());
        ArrayList<Member> members = team.getList();
        for (Member member : members) {
            if (member == null) {continue;}
            if (member.isInTeam() == false) {continue;}

            if (member.getLevel() >= shuaDaoSet.getMinLevel()) {continue;}

            if (levelNotEnoughNames.length() > 0) {
                levelNotEnoughNames.append("、");
            }
            levelNotEnoughNames.append(member.getName());
        }
        if (levelNotEnoughNames.length() > 0) {
            return MessageFormat.format(FIGHT_LEVEL_NOT_ENOUGH, levelNotEnoughNames, shuaDaoSet.getMinLevel());
        }

        /**判断所有人等级差是否超过限制*/
        for(int i=0, count=members.size(); i<count; i++) {
            Member member = members.get(i);
            if(member == null || member.isInTeam() == false) {continue;}

            for (int j=i; j<count; j++) {
                Member otherMember = members.get(j);
                if(otherMember == null || otherMember.isInTeam() == false) {continue;}

                if (Math.abs(member.getLevel()-otherMember.getLevel()) > MAX_LEVEL_DIFF) {
                    return MessageFormat.format(FIGHT_TEAM_LEVEL_DIFF_MORE, MAX_LEVEL_DIFF, shuaDaoSet.getShuaDaoName());
                }
            }
        }


        return null;
    }

    @Override
    public void doStartFight(Role role, TaskSet taskSet, NPC bossNpc) {
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());

        List<BossParam> bossParamList = newBossParamList(role, bossNpc, shuaDaoSet);
        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role), shuaDaoSet.getFightTaskId(), bossNpc.getId());
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        bossService.startFightToBoss(role, bossFightParam);
    }

    @Override
    protected int getFightType(Role role) {
        return Const.fightType_shuadao;
    }

    private List<BossParam> newBossParamList(Role role, NPC npc, ShuaDaoSet shuaDaoSet) {
        List<BossParam> bossParamList = new ArrayList<>();
        /**有指定怪数量时，使用指定数量。否则按规则生成*/
        int count = shuaDaoSet.getBossTotalCount();
        if (count <= 0) {
            count = getBossCount(role);
        }

        /**npc对应的加在最前面*/
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        BossSet bossSet = null;
        for (int i=0; i<shuaDaoSet.getNpcBossCount(); i++) {
            bossSet = bossService.getBossSet(npc.getBossSetName());
            bossParamList.add(new BossParam(bossSet, npc.getName()));
        }

        List<String> bossNames = new ArrayList<>();
        bossNames.addAll(shuaDaoSet.getSmallBossNames());
        bossNames.remove(npc.getBossSetName());
        /**加count-已加的数量的小怪*/
        for (int i=shuaDaoSet.getNpcBossCount(); i<count; i++) {
            int index = ThreadLocalRandom.current().nextInt(bossNames.size());
            bossSet = bossService.getBossSet(bossNames.get(index));

            /**有别名时，用别名。否则用bossSet的name*/
            String name = (shuaDaoSet.getSmallAlias() != null ? shuaDaoSet.getSmallAlias() : bossSet.getName());
            bossParamList.add(new BossParam(bossSet, name));
        }

        return bossParamList;
    }

    @Override
    protected void addActivityFinishCount(Role role, TaskSet taskSet) {
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        /**次数+1*/
        SpringUtils.getBean(ActivityService.class).addFinishCount(role, shuaDaoSet.getActivityType(), 1);

        /**增加刷道积分*/
        addScore(role, shuaDaoSet);

        log.warn("增加活动完成次数：roleId:{}, finishCount:{}", role.getRoleId(), SpringUtils.getBean(ActivityService.class).getFinishCount(role, shuaDaoSet.getActivityType()));
    }

    /**增加刷道积分*/
    private void addScore(Role role, ShuaDaoSet shuaDaoSet) {
        /**降妖且80级以上不能获得积分*/
        if (shuaDaoSet instanceof XiangYaoShuaDaoSet && role.getLevel() > 80) {
            return ;
        }

        /**加刷道积分*/
        int addScore = 0;
        if (SpringUtils.getActivityService().isOpenJJRLL(role)) {
            /**开启开启急急如律令人话，则按满怪处理*/
            addScore = 10 * shuaDaoSet.getCountRate();
        } else {
            addScore = role.getActivity().getMonsterCount() * shuaDaoSet.getCountRate();
        }

        role.getActivity().setShuaDaoScore(role.getActivity().getShuaDaoScore() + addScore);
    }

    @Override
    protected void giveReward(Role role, NutMap reward, TaskSet taskSet,int currPetId) {
        // TODO 拷贝了之前的降妖发奖代码，后面再修改


        // 刷道 有道行 有潜能 有随机装备(第十轮必给) 有代金券(会员给金钱)
        TeamService teamService = SpringUtils.getBean(TeamService.class);
        Team team = teamService.getTeam(role.getRoleId());
        if (team == null) {
            log.warn("刷道发奖玩家没有组队，roleId:{}", role.getRoleId());
            MessagePusher.pushMessage(role, new RespMsg(REWARD_NOT_IN_TEAM));
            return;
        }

        /**没有接取任务，不能获得奖励*/
        if (role.getTask().isAccepted(taskSet.getId()) == false) {
            log.warn("刷道发奖玩家没有接取任务，roleId:{}", role.getRoleId());
            return ;
        }
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        recordUsedTime(role, shuaDaoSet);
//        logger.error("记录刷道耗时==={}=={}",role.getName(),shuaDaoSet.getActivityType());
        int finishCount = activityService.getFinishCount(role, shuaDaoSet.getActivityType());

        int step = ((finishCount-1) % 10 + 1);
        /**第10轮时*/
        if ((step) == 200) {
            // 奖励装备
            short roleLevel = role.getLevel();
            String temp = roleLevel + "";
            if (temp.length() == 3) {
                roleLevel = Short.parseShort(temp.substring(0, 2) + 0);
            } else {
                roleLevel = Short.parseShort(temp.substring(0, 1) + 0);
            }
            short newPos = bagService.getPos(role, false);
            if (newPos > 0) {
                equipService.getNotIdentifyEquip(roleLevel, role, newPos);
            }
        }
        int daohang = new Double(reward.getInt("rewardDaohang", 0)
                * ((step * 0.1 + 1))).intValue();
        int qianneng = new Double(reward.getInt("rewardQianneng", 0)
                * ((step * 0.1 + 1))).intValue();
        int money = new Double(reward.getInt("rewardMoney", 0)
                * ((step * 0.1 + 1))).intValue();
        int petWuxue = new Double(reward.getInt("petRewardWuxue")
                * ((step * 0.1 + 1))).intValue();
        int size = reward.getInt("size", 1);
        Calendar calendarStart = Calendar.getInstance();
        int curHour24 = calendarStart.get(Calendar.HOUR_OF_DAY);
        int minute = calendarStart.get(Calendar.MINUTE);
        if (curHour24 == 20 || (curHour24 == 19 && minute >= 30) || (curHour24 == 21 && minute <= 30)) {
            int old = daohang;
            daohang = daohang * 2;
            //MessagePusher.pushMessage(role,new RespNotifyMiscEx("全局双倍道行开启，刷道所获得道行翻倍，原来增加道行#R"+old+"#n，双倍后道行#R"+daohang));
        }
        if (step == 5){
            // 记录第五轮的结果
            NutMap nutMap = null;
            if (taskSet.getNpcName().equals("通灵道人")){
                nutMap = role.getOfflineNotice().getNutMapXiangyao();
            }else if (taskSet.getNpcName().equals("陆压真人")){
                nutMap = role.getOfflineNotice().getNutMapFumo();
            }else if (taskSet.getNpcName().equals("清微真人")){
                nutMap = role.getOfflineNotice().getNutMapFeixian();
            }
            if (nutMap != null){
                nutMap.setv("daohang",daohang);
                nutMap.setv("qianneng",qianneng);
                nutMap.setv("money",money);
                nutMap.setv("petWuxue",petWuxue);
                nutMap.setv("size",size);
            }

        }
        RoleService roleService = SpringUtils.getRoleService();
        int jijirulvling = role.getPropsStatus().getInt("manguaiStatus", 0);
        int kaiqi = role.getPropsStatus().getInt("manguai", 0);
        NutMap nutMap = role.getPropsStatus();
        {
           if (jijirulvling > 0 && kaiqi > 0) {
                kaiqi = kaiqi - 1;
//                int size = reward.getInt("size", 1);
                role.getPropsStatus().setv("manguai", kaiqi);
                money = money / size * 10;
                daohang = daohang / size * 10;
                qianneng = qianneng / size * 10;
            }
            //MessagePusher.pushMessage(role, new RespNotifyMiscEx(stringBuilder.toString()));
        }
        //宠风散
        add(daohang,qianneng,money,petWuxue,size,role,1);
        int value = new Random().nextInt(600);
        if (value == 1){
            SpringUtils.getBean(EquipService.class).addMall("道行盛典礼包", false, role);
            String content = "惊闻玩家#R" + role.getName() + "#n在#R刷道时#n，获得#R" + "道行盛典礼包" + "#n！真是可喜可贺！#51 #82";
            SpringUtils.getChatService().sendAdnotice(content);
        }
        value = new Random().nextInt(10000);
        if (value == 1){
            SpringUtils.getBean(EquipService.class).addMall("召唤令·上古神兽", false, role);
            String content = "惊闻玩家#R" + role.getName() + "#n在#R刷道时#n，获得#R" + "召唤令·上古神兽" + "#n！真是可喜可贺！#51 #82";
            SpringUtils.getChatService().sendAdnotice(content);
        }
    }


    public void add(int daohang,int qianneng,int money,int petWuxue,int size,Role role,int round) {
        BagService bagService = SpringUtils.getBean(BagService.class);
        EquipService equipService = SpringUtils.getBean(EquipService.class);
        PetService petService = SpringUtils.getBean(PetService.class);
        RoleService roleService = SpringUtils.getRoleService();
        NutMap nutMap = role.getPropsStatus();
        Pet pet = petService.getPetById(role.getPetBox().getFightPetId(), role);
        if (pet != null) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("获得基础道武学#R" + roleService.getWuxue(petWuxue, pet) + "点#n");
            int point = nutMap.getInt("pet");
           if (nutMap.getInt("petStatus") == 1 && point >= 4 * round) {
                nutMap.setv("pet", point - 4 * round);
                role.save();
                petWuxue = petWuxue * 2;
                stringBuilder.append("，开启#R宠风散#n后获得武学增加至#R" + roleService.getWuxue(petWuxue, pet) + "点#n");
            }
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(stringBuilder.toString()));
            roleService.addPetMatiral(role, pet, petWuxue);
        }

        int point = nutMap.getInt("role");
        // 超级仙风散
        ArtifactService artifactService = SpringUtils.getBean(ArtifactService.class);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("获得基础道行#R" + roleService.getTao(daohang, role) + "点#n");
       if (nutMap.getInt("roleStatus") == 1 && point >= 4 * round) {
            nutMap.setv("role", point - 4 * round);
            money = money * 2;
            daohang = daohang * 2;
            qianneng = qianneng * 2;
            stringBuilder.append("，开启#R超级仙风散#n后获得道行增加至#R" + roleService.getTao(daohang, role) + "点#n");
            artifactService.addArtifactExp(true, role);
        } else {
            artifactService.addArtifactExp(false, role);
        }
        MessagePusher.pushMessage(role, new RespNotifyMiscEx(stringBuilder.toString()));
       //队长多给百分之5
        if(teamService.isTeamLeader(role)){
            daohang = (int)(daohang*1.05);
            qianneng = (int)(qianneng*1.05);
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("作为队长额外获得5%的道行、潜能。"));
        }
        roleService.addPot(role, qianneng);
        //增加道行
        double superVipRate = SpringUtils.getBean(SuperVipService.class).getSuperVipRate(role);
        if(superVipRate > 1){
            PlayerExtendBox extendBox = role.getExtendBox();
            int vipLv = extendBox.getSuperVipType();
            daohang =(int) (daohang * superVipRate);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("您当前是#RVIP"+vipLv+"#n,享受刷道加成:#R"+superVipRate+"#n倍"));
        }
        roleService.addTao(role, daohang);
//        roleService.addTaoMsg(role, daohang,stringBuilder.toString());
        int shuaDaoTotalCount = getShuaDaoTotalCount(role);
        /**根据刷道次数给金币，大于一定刷道次数时不再获得金币*/
        if (shuaDaoTotalCount < MIN_COUNT_NO_MONEY) {
            /**减半*/
            if (shuaDaoTotalCount >= MIN_COUNT_HALF_MONEY) {
                money = money / 2;
            }
            roleService.addMoney(role, money);
        }

        role.save();
    }



    /**获得刷道的总次数*/
    public int getShuaDaoTotalCount(Role role) {
        int totalCount = ActivityDataPool.shuaDaoMap.values().stream().mapToInt(shuaDaoSet -> (activityService.getFinishCount(role, shuaDaoSet.getActivityType())) * shuaDaoSet.getCountRate()).sum();
        return totalCount;
    }

    @Override
    protected void doBeforeDelete(Role role, TaskSet taskSet) {
//        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(taskSet.getId());
        /**记录耗时*/

//        logger.error("记录刷道耗时==={}=={}",role.getName(),shuaDaoSet.getActivityType());
    }

    /**记录这轮完成 耗时*/
    private void recordUsedTime(Role role, ShuaDaoSet shuaDaoSet) {
        if (teamService.isTeamLeader(role)) {
            Integer timeSecond = getUsedTime(role, shuaDaoSet);
            if (timeSecond == null) {return ;}

            Team team = teamService.getTeam(role.getRoleId());
            ArrayList<Member> members = team.getList();
            for (Member member : members) {
                if (member == null) {continue;}
                if (!member.isInTeam()) {continue;}

                if (member.getRoleId() != role.getRoleId()) {
                    Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getUid());
                    if(memberRole==null){
                        continue;
                    }
                    ThreadLocalUtil.addLocalTask(memberRole, () -> recordUseTimeForSingle(memberRole, shuaDaoSet, timeSecond));
                } else {
                    recordUseTimeForSingle(role, shuaDaoSet, timeSecond);
                }
            }
        }
    }

    /**为个人记录这轮完成耗时*/
    private void recordUseTimeForSingle(Role role, ShuaDaoSet shuaDaoSet, int timeSecond) {
        Map<String, LinkedList<Integer>> shuaDaoUsedTime = role.getActivity().getShuaDaoUsedTime();
        LinkedList<Integer> times = shuaDaoUsedTime.computeIfAbsent(shuaDaoSet.getActivityType().getActivityId(), k -> new LinkedList<>());

        times.add(timeSecond);

        /**10轮为1个周期计算*/
        if (times.size() >= 10) {
            if (times.size() > 10) {
                /**删除第1个*/
                times.remove(0);
            }

            calTenShuaDaoUsedTime(role, shuaDaoSet, times);
        }

        role.save();
    }

    /**计算最近十轮刷道时间*/
    private void calTenShuaDaoUsedTime(Role role, ShuaDaoSet shuaDaoSet, LinkedList<Integer> times) {
        /**获得十轮所用时间总和*/
        int total = times.stream().mapToInt(time -> time).sum();
        if(role.isAi(role)){
            return;
        }

        /**更新最近十轮的耗时，并更新到排行榜数据中*/
        role.getActivity().getTenShuaDaoUsedTime().put(shuaDaoSet.getActivityType().getActivityId(), total);

        switch (shuaDaoSet.getRankKey()) {
            case Const.xiangyaoRank:
                SpringUtils.getBean(XiangYaoRankHandler.class).update(role.getGid(), new ShuaDaoRankRecord(role.getGid(), total, role.getLevel(), role.getPartyName(), role.getName(), role.getPolar(), role.getRoleIcon()));
                break;
            case Const.fumoRank:
                SpringUtils.getBean(FuMoRankHandler.class).update(role.getGid(), new ShuaDaoRankRecord(role.getGid(), total, role.getLevel(), role.getPartyName(), role.getName(), role.getPolar(), role.getRoleIcon()));
                break;
            case Const.feixianduxieRank:
                SpringUtils.getBean(FeiXianDuXieRankHandler.class).update(role.getGid(), new ShuaDaoRankRecord(role.getGid(), total, role.getLevel(), role.getPartyName(), role.getName(), role.getPolar(), role.getRoleIcon()));
                break;
            case Const.xiangyaoRank2:
                SpringUtils.getBean(XiangYaoRankHandler.class).update(role.getGid(), new ShuaDaoRankRecord(role.getGid(), total, role.getLevel(), role.getPartyName(), role.getName(), role.getPolar(), role.getRoleIcon()));
                break;
            case Const.fumoRank2:
                SpringUtils.getBean(FuMo2RankHandler.class).update(role.getGid(), new ShuaDaoRankRecord(role.getGid(), total, role.getLevel(), role.getPartyName(), role.getName(), role.getPolar(), role.getRoleIcon()));
                break;
            case Const.feixianduxieRank2:
                SpringUtils.getBean(FeiXianDuXie2RankHandler.class).update(role.getGid(), new ShuaDaoRankRecord(role.getGid(), total, role.getLevel(), role.getPartyName(), role.getName(), role.getPolar(), role.getRoleIcon()));
                break;
        }
    }


    /**获得刷道对应的耗时，单位秒*/
    private Integer getUsedTime(Role role, ShuaDaoSet shuaDaoSet) {
        /**当前时间与NPC创建时间 之前的差值 就是耗时*/
        NewTaskService taskService = SpringUtils.getBean(NewTaskService.class);
        TaskSet taskSet = taskService.getTaskSet(shuaDaoSet.getFightTaskId(), role);
        int taskNpcId = role.getTask().getTaskNpcId(taskSet.getId());

        MapService mapService = SpringUtils.getBean(MapService.class);
        NPC npc = mapService.getNpc(taskNpcId);
        if (npc != null) {
            return (int)((System.currentTimeMillis() - npc.getCreateTime()) / TimeUtil.ONE_SECOND);
        }

        return null;
    }

    @Override
    protected void doAfterDelete(Role role, TaskSet taskSet) {
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        TaskSet guideTaskSet = taskService.getTaskSet(shuaDaoSet.getGuideTaskId(), role);
        TaskInfo taskInfo = getGuideTaskInfo(role, guideTaskSet);

        /**获得指引任务发给玩家引导玩家去NPC处接任务*/
        if (SpringUtils.getActivityService().getFinishCount(role, shuaDaoSet.getActivityType()) % 10 != 0) {
            taskService.pushTaskInfo(role, taskInfo);
        }

        if (teamService.isTeamLeader(role)) {
            /**自动寻路到NPC*/
            autoWalk(role, taskInfo);
        }
    }

    @Override
    public boolean isCreateNpcForFight(TaskSet taskSet) {
        return true;
    }

    @Override
    public boolean isDeleteTaskTeamChange() {
        return true;
    }

    @Override
    public boolean isDeleteTaskLogout() {
        return true;
    }

    private TaskInfo getGuideTaskInfo(Role role, TaskSet taskSet) {
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        ShuaDaoSet shuaDaoSet = getShuaDaoSetByTask(role,taskSet.getId());
        int doStep = (activityService.getFinishCount(role, shuaDaoSet.getActivityType())%10) + 1;
        log.debug("发送引导任务,roleId:{} , doStep:{}", role.getRoleId(), doStep);
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setQuit((short) taskSet.getGiveUp());// 是否可以放弃
        taskInfo.setTaskName(taskSet.getTaskName());
        taskInfo.setShow_name(MessageFormat.format( taskSet.getTaskName(),doStep));
        taskInfo.setTaskInfo(MessageFormat.format( taskSet.getTaskJieshao(),doStep));
        taskInfo.setTaskZhiyin(taskSet.getTaskZhiyin());
        taskInfo.setTaskJiangli(taskSet.getTaskGift());
        return taskInfo;

    }


    public void sendNpcContent(Role role, NPC bossNpc) {
        String content = getNpcContent(role, bossNpc);
        SpringUtils.getNpcService().sendNpcContent(role, bossNpc, content);
    }

    /**从传入map中获得对应数据*/
    public void loadCommonSet(Map<String ,String> commonSetMap) {
        String value = commonSetMap.get("shuadao_reward_set");
        List<ShuaDaoRewardSet> shuaDaoRewardSets = Json.fromJsonAsList(ShuaDaoRewardSet.class, value);
        ActivityDataPool.shuaDaoRewardSets = shuaDaoRewardSets;
    }

    /**重置刷道积分并设置把未领取奖励发到邮箱*/
    public void resetScoreAndSendReward(Role role) {
        sendReward(role);

        /**剩余积分*/
        ShuaDaoRewardSet shuaDaoRewardSet = ActivityDataPool.shuaDaoRewardSets.get(0);
        int remainScore = role.getActivity().getShuaDaoScore() % shuaDaoRewardSet.getScore();
        role.getActivity().setShuaDaoScore(remainScore);

        /**领奖奖励清除*/
        role.getActivity().getShuaDaoFetchStatus().clear();

        role.save();
    }

    /**把所有未领取奖励发到玩家邮箱*/
    public void sendReward(Role role) {
        Map<String, Integer> rewards = new HashMap<>();
        for (ShuaDaoRewardSet shuaDaoRewardSet : ActivityDataPool.shuaDaoRewardSets) {
            /**已经领取，则跳过*/
            if (role.getActivity().getShuaDaoFetchStatus().getOrDefault(shuaDaoRewardSet.getScore(), false)) {continue;}

            if (role.getActivity().getShuaDaoScore() >= shuaDaoRewardSet.getScore()) {
                Map<String, Integer> items = shuaDaoRewardSet.getItems();
                for (Map.Entry<String, Integer> entry : items.entrySet()) {
                    int count = rewards.get(entry.getKey()) != null ? rewards.get(entry.getKey()) + entry.getValue() : entry.getValue();
                    rewards.put(entry.getKey(), count);
                }
            }
        }

        if (rewards.size() == 0) {
            return ;
        }


        String title = "刷道积分奖励";
        String content = "刷道积分奖励";
        Mail mail = SpringUtils.getMailService().createMail(title, content, 30 * TimeUtil.ONE_DAY);

        /**附件*/
        for (Map.Entry<String, Integer> entry: rewards.entrySet()) {
            if (Const.CHONG_FEN_SAN_ITEM_NAME.equals(entry.getKey())) {
                mail.getDatas().add(NutMap.NEW().setv("data", MessageFormat.format("#I宠风散点数|{0}#r{1}#I", entry.getKey(), entry.getValue())).setv("type", Const.mailPointItem).setv("name", entry.getKey()).setv("value", entry.getValue()));
            } else if (Const.ZI_QI_HONG_MENG_ITEM_NAME.equals(entry.getKey())) {
                mail.getDatas().add(NutMap.NEW().setv("data", MessageFormat.format("#I紫气鸿蒙点数|{0}#r{1}#I", entry.getKey(), entry.getValue())).setv("type", Const.mailPointItem).setv("name", entry.getKey()).setv("value", entry.getValue()));
            } else {
                mail.getDatas().add(NutMap.NEW().setv("data", MessageFormat.format("#I物品|{0}#r{1}#I", entry.getKey(), entry.getValue())).setv("type", Const.rewardWupin).setv("petName", entry.getKey()).setv("value", entry.getValue()));
            }
        }

        SpringUtils.getBean(MailService.class).sendNewMail(role, mail);
    }

    /**领取奖励*/
    public void fetchReward(Role role, byte type, byte index) {
        ShuaDaoRewardSet shuaDaoRewardSet = ActivityDataPool.shuaDaoRewardSets.get(index);
        if (shuaDaoRewardSet == null) {
            return ;
        }

        Boolean status = role.getActivity().getShuaDaoFetchStatus().get(shuaDaoRewardSet.getScore());
        if (status != null && status) {
            /**已经获得奖励*/
            return ;
        }

        /**积分不够时，返回*/
        if (role.getActivity().getShuaDaoScore() < shuaDaoRewardSet.getScore()) {
            return ;
        }

        if (role.popTempCache("check_shuadao_score_fetch_max") == null) {
            /**检测宠风散点数和紫气鸿蒙点数是否超过上限，超过时提示*/
            StringBuilder stringBuilder = null;
            String limit_tip = "{0}将超出上限，超出上限的{1}点将被没收，";
            Map<String, Integer> items = shuaDaoRewardSet.getItems();
            for (Map.Entry<String, Integer> entry : items.entrySet()) {
                String name = entry.getKey();
                int count = entry.getValue();

                if (Const.CHONG_FEN_SAN_ITEM_NAME.equals(name)) {
                    if (role.getPropsStatus().getInt("pet", 0) + count > PointItem.CHONG_FENG_SAN.getMax()) {
                        if (stringBuilder == null) {stringBuilder = new StringBuilder();}
                        int more = role.getPropsStatus().getInt("pet", 0) + count-PointItem.CHONG_FENG_SAN.getMax();
                        stringBuilder.append(MessageFormat.format(limit_tip, name, more));
                    }
                } else if (Const.ZI_QI_HONG_MENG_ITEM_NAME.equals(name)) {
                    if (role.getPropsStatus().getInt("ziqi", 0) + count > PointItem.ZI_QI_HONG_MENG.getMax()) {
                        if (stringBuilder == null) {stringBuilder = new StringBuilder();}
                        int more = role.getPropsStatus().getInt("ziqi", 0) + count-PointItem.ZI_QI_HONG_MENG.getMax();
                        stringBuilder.append(MessageFormat.format(limit_tip, name, more));
                    }
                }
            }

            if (stringBuilder != null) {
                String tip = "领取后" + stringBuilder + "是否继续领取？";

                role.setConfirm(new FetchShuaDaoRewardConfirm(type, index));
                role.pushTempCache("check_shuadao_score_fetch_max", true);

                RespConfirm respConfirm = new RespConfirm();
                respConfirm.setTips(tip);
                respConfirm.setConfirm_type("");
                MessagePusher.pushMessage(role, respConfirm);

                return ;
            }
        }



        /**设置已经领奖状态*/
        role.getActivity().getShuaDaoFetchStatus().put(shuaDaoRewardSet.getScore(), true);

        /**给奖励*/
        Map<String, Integer> items = shuaDaoRewardSet.getItems();
        for (Map.Entry<String, Integer> entry : items.entrySet()) {
            String name = entry.getKey();
            int count = entry.getValue();

            if (Const.CHONG_FEN_SAN_ITEM_NAME.equals(name)) {
                SpringUtils.getBean(PointItemService.class).addChongFengSan(role, count);
            } else if (Const.ZI_QI_HONG_MENG_ITEM_NAME.equals(name)) {
                SpringUtils.getBean(PointItemService.class).addZiQiHongMeng(role, count);
            } else {
                SpringUtils.getEquipService().addMall(name, true, role, count);
            }
        }

        pushRespOpenShuadaoDlg(role);
    }

    public void pushRespOpenShuadaoDlg(Role role) {
        RespOpenShuadaoDlg respOpenShuadaoDlg = getRespOpenShuadaoDlg(role);
        MessagePusher.pushMessage(role, respOpenShuadaoDlg);
    }

    public RespOpenShuadaoDlg getRespOpenShuadaoDlg(Role role) {
        RespOpenShuadaoDlg respOpenShuadaoDlg = new RespOpenShuadaoDlg();
        respOpenShuadaoDlg.setScore(role.getActivity().getShuaDaoScore());
        BitSet fetchBitSet = BitSet.NEW();
        int index = 0;
        for (int i=0, size=ActivityDataPool.shuaDaoRewardSets.size(); i<size; i++) {
            index = i + 1;
            ShuaDaoRewardSet shuaDaoRewardSet = ActivityDataPool.shuaDaoRewardSets.get(i);
            Boolean status = role.getActivity().getShuaDaoFetchStatus().get(shuaDaoRewardSet.getScore());
            if (status != null && status) {
                fetchBitSet.setBit(index);
            }
        }
        respOpenShuadaoDlg.setFetchState(fetchBitSet.getI32());
        return respOpenShuadaoDlg;
    }

    public void pushShuaDaoPropsStatus(Role role) {
        ArrayList<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(312, role.getPropsStatus().getInt("manguai", 0)));
        list.add(new FiedValue(900, role.getPropsStatus().getInt("ziqi", 0)));
        list.add(new FiedValue(3002, role.getPropsStatus().getInt("pet", 0)));
        list.add(new FiedValue(918, role.getPropsStatus().getInt("ruyi", 0)));
        RespUpdate respUpdate = new RespUpdate(role.getRoleId(), list);
        MessagePusher.pushMessage(role, respUpdate);
    }
}
